<?php
/**
 * 提现到微信零钱
 * xionggan
 * 2019-06-24
 */

namespace service\transfer\way;

use http\Curl;
use think\Exception;
use think\facade\Log;
use think\facade\Env;
use think\facade\Config;
use service\TransferService;

class transferWayLQ implements transferWayInt
{

    protected $api_url  = null;
    protected $mchid    = null;
    protected $appid    = null;
    protected $appkey   = null;

    public function __construct($type)
    {
        $this->getConfig($type);
    }

    public function transferWay($data)
    {
        $params = [
            'mch_appid'         => $this->appid,
            'mchid'             => $this->mchid,
            'device_info'       => $data['device_sn'],
            'nonce_str'         => md5($data['transfer_sn'].$data['user_id']),
            'partner_trade_no'  => $data['transfer_sn'],
            'openid'            => $data['open_id'],
            'check_name'        => $data['check_name'] == 1 ? 'FORCE_CHECK' : 'NO_CHECK',
            're_user_name'      => $data['real_name'] ?? '',
            'amount'            => $data['amount'],
            'desc'              => $data['desc'],
            'spbill_create_ip'  => $data['ip'],
        ];

        $params['sign'] = $this->getSign($params);
        $post_xml = $this->createXMLStr($params);

        $curl = new Curl();
        $curl->setSslCert(ROOT_DIR.'/config/wxcert/apiclient_cert.pem');
        $curl->setSslKey(ROOT_DIR.'/config/wxcert/apiclient_key.pem');

        $data = $curl->request(
            $this->api_url, $post_xml, 'POST', false, ['Content-Type: text/xml']
        );

        if ($data['httpcode'] != 200) {
            throw new Exception('网络故障');
        }

        $res = new \SimpleXMLElement($data['data']);

        if (!isset($res->return_code) || $res->return_code != 'SUCCESS') {
            throw new Exception('发起提现失败');
        }

        if (!isset($res->result_code) || $res->result_code != 'SUCCESS') {
            throw new Exception('err_code:'.$res->err_code.', err_code_des:'.$res->err_code_des);
        }

        return [
            'transfer_sn'   => $res->partner_trade_no->__toString(),
            'payment_no'    => $res->payment_no->__toString(),
            'payment_time'  => strtotime($res->payment_time->__toString()) ?? 0,
        ];
    }

    public function getConfig($type)
    {
        $this->api_url  = Env::get('transfer_'.$type.'.lq_api_url');
        $this->mchid    = Env::get('transfer_'.$type.'.lq_mchid');
        $this->appid    = Env::get('transfer_'.$type.'.lq_mch_appid');
        $this->appkey   = Env::get('transfer_'.$type.'.lq_mch_appkey');

        if (empty($this->api_url)) {
            throw new Exception('微信零钱提现，缺少配置：api_url');
        }

        if (empty($this->mchid)) {
            throw new Exception('微信零钱提现，缺少配置：mchid');
        }

        if (empty($this->appid)) {
            throw new Exception('微信零钱提现，缺少配置：appid');
        }

        if (empty($this->appkey)) {
            throw new Exception('微信零钱提现，缺少配置：appkey');
        }
    }

    protected function getSign($params)
    {
        $str = '';
        ksort($params);

        foreach ($params as $key => $value) {
            if ($value !== '') {
                $str.= $key."=".$value."&";
            }
        }
        $str .= "key=".$this->appkey;
        return strtoupper(md5($str));
    }

    protected function createXmlStr(array $params)
    {
        $xml = new \SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><xml></xml>');
        foreach ($params as $key => $value) {
            $xml->addChild($key, $value);
        }
        return $xml->asXML();
    }

}
